from flask import render_template, session, current_app, g, abort, request, jsonify

from info import constants, db
from info.models import News, User

from info.modules.news import news_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blu.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注或者取消关注用户"""

    # 0. 取到自己的登录信息
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="未登录")

    # 1. 取参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2. 判断参数
    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 取到要被关注的用户
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    # 4. 根据要执行的操作去修改对应的数据
    if action == "follow":
        if other not in user.followed:
            # 当前用户的关注列表添加一个值
            user.followed.append(other)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前用户已被关注")
    else:
        # 取消关注
        if other in user.followed:
            user.followed.remove(other)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前用户未被关注")

    return jsonify(errno=RET.OK, errmsg="操作成功")


# 收藏新闻
@news_blu.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    """
    1.用户信息获取
    2.数据校验
    :return:
    """
    user = g.user
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登陆')

    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if action not in ('collect', 'cancel_collect'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻信息不存在')

    if action == 'collect':
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存失败')
    return jsonify(errno=RET.OK, errmsg='提交成功')


@news_blu.route('/<int:news_id>')
@user_login_data
def news_blu(news_id):
    # 查询用户登录信息
    user = g.user
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)

    except Exception as e:
        current_app.logger.error(e)
    print(news_list)
    click_news_list = []

    for news in news_list:
        click_news_list.append(news.to_basic_dict())
    # 查询新闻数据
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        abort(404)
        # 更新新闻的点击次数
    news.clicks += 1
    # 当前登录用户是否关注当前新闻作者
    is_followed = False
    # 判断用户是否收藏该新闻，默认值为False
    is_collected = False
    # 判断用户是否收藏过该新闻

    if user:
        if news in user.collection_news:
            is_collected = True
    # if 当前新闻有作者，并且 当前登录用户已关注过这个用户
    if news.user and user:
        # if user 是否关注过 news.user
        if news.user in user.followed:
            is_followed = True
        # if news.user.followers.filter(User.id == user.id).count() > 0:
        #     is_followed = True

    data = {
        'is_collected': is_collected,
        'click_news_list': click_news_list,
        'news': news.to_dict(),
        'user_info': user.to_dict() if user else None,
        'is_followed': is_followed

    }
    return render_template('news/detail.html', data=data)
